<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="应用标识" prop="clientId">
        <el-input
          v-model="queryParams.clientId"
          placeholder="请输入应用标识"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="应用名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入应用名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:application:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:application:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:application:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:application:export']"
        >导出</el-button>
      </el-col>-->
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange" :max-height="height">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template scope="scope"> <span>{{scope.$index + (queryParams.pageNum - 1) * queryParams.pageSize + 1}} </span> </template>
      </el-table-column>
      <el-table-column label="应用标识" align="center" prop="clientId" :show-overflow-tooltip="true" min-width="80"/>
      <el-table-column label="应用名称" align="center" prop="clientName" :show-overflow-tooltip="true"/>
      <el-table-column label="应用密钥" align="center" prop="clientSecret" :show-overflow-tooltip="true" />
      <el-table-column label="回调地址" align="center" prop="webServerRedirectUri" :show-overflow-tooltip="true" />
      <el-table-column label="授权模式" align="center" prop="authorizedGrantTypes" :show-overflow-tooltip="true" :formatter="typeFormat"/>
      <el-table-column label="自动审批" align="center" prop="approval" :formatter="approvalFormat"/>
      <el-table-column label="令牌时效(s)" align="center" prop="accessTokenValidity"  width="100" />
      <el-table-column label="刷新时效(s)" align="center" prop="refreshTokenValidity" width="100"/>
      <el-table-column label="注册时间" align="center" prop="createTime" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册人" align="center" prop="createName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:application:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:application:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改终端配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="应用标识" prop="clientId">
          <el-input v-model="form.clientId" placeholder="请输入应用标识" />
        </el-form-item>
        <el-form-item label="应用名称" prop="clientName">
          <el-input v-model="form.clientName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用密钥" prop="clientSecretStr">
          <el-input v-model="form.clientSecretStr" placeholder="请输入应用密钥" />
        </el-form-item>
        <el-form-item label="回调地址" prop="webServerRedirectUri">
          <el-input v-model="form.webServerRedirectUri" placeholder="请输入回调地址" />
        </el-form-item>
        <el-form-item label="自动审批" prop="approval">
          <el-radio-group v-model="form.approval">
            <el-radio
              v-for="dict in approvalOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="授权模式" prop="authorizedGrantTypes">
          <el-checkbox-group v-model="form.authorizedGrantTypes">
            <el-checkbox
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="令牌时效" prop="accessTokenValidity">
          <el-input-number v-model="form.accessTokenValidity" placeholder="请输入令牌时效(s)" />
        </el-form-item>
        <el-form-item label="刷新时效" prop="refreshTokenValidity">
          <el-input-number v-model="form.refreshTokenValidity" placeholder="请输入刷新时效(s)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApplication, getApplication, delApplication, addApplication, updateApplication, exportApplication } from "@/api/system/application";

export default {
  name: "Application",
  data() {
    return {
      height: (document.documentElement.clientHeight || document.body.clientHeight)-260,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 终端配置表格数据
      applicationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审批数据字典
      approvalOptions: [],
      // 授权模式数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientId: null,
        clientName: null,
        clientSecret: null,
        clientSecretStr: null,
        resourceIds: null,
        scope: null,
        authorizedGrantTypes: null,
        webServerRedirectUri: null,
        authorities: null,
        accessTokenValidity: null,
        refreshTokenValidity: null,
        additionalInformation: null,
        autoapprove: null,
        createName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        clientId: [
          { required: true, message: "应用标识不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_oauth_client_details_approval").then(response => {
      this.approvalOptions = response.data;
    });
    this.getDicts("sys_oauth_client_details_types").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询终端配置列表 */
    getList() {
      this.loading = true;
      listApplication(this.queryParams).then(response => {
        this.applicationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applicationId: null,
        clientId: null,
        clientName: null,
        clientSecret: null,
        clientSecretStr: null,
        resourceIds: null,
        scope: null,
        authorizedGrantTypes: [],
        webServerRedirectUri: null,
        approval: '0',
        authorities: null,
        accessTokenValidity: null,
        refreshTokenValidity: 1800,
        additionalInformation: null,
        autoapprove: null,
        createName: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applicationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加终端配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applicationId = row.applicationId || this.ids
      getApplication(applicationId).then(response => {
        this.form = response.data;
        if (response.data.authorizedGrantTypes != null){
          this.form.authorizedGrantTypes = response.data.authorizedGrantTypes.split(",");
        }
        this.open = true;
        this.title = "修改终端配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.applicationId != null) {
            this.form.authorizedGrantTypes = this.form.authorizedGrantTypes.toString();
            updateApplication(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            this.form.authorizedGrantTypes = this.form.authorizedGrantTypes.toString();
            addApplication(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applicationIds = row.applicationId || this.ids;
      this.$confirm('是否确认删除终端配置编号为"' + applicationIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delApplication(applicationIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有终端配置数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportApplication(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    // 审批字典翻译
    approvalFormat(row, column) {
      return this.selectDictLabel(this.approvalOptions, row.approval);
    },
    // 授权模式字典翻译
    typeFormat(row, column) {
      return this.selectDictLabels(this.typeOptions, row.authorizedGrantTypes);
    },
  }
};
</script>
